
import {
  getAge
} from '../../third-utils/time/index.js';

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ec: {

      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
    },
    ec1: {

      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
    },
    babyId: '',
    babyInfo: '',
    curCate: 1,
    categroyList: ['记录列表', '身高曲线', '体重曲线', ],
    infoList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    this.setData({
      babyId: e.babyId
    })
    // 获取组件
    this.ecComponent = this.selectComponent('#chart');
    this.init()
    // 获取组件
    this.ecComponent1 = this.selectComponent('#chart1');
    this.init1()
  },
  onShow() {
    this.initData()

  },

  // 点击按钮后初始化图表
  init1: function () {
    this.ecComponent1.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      this.setOption(chart, '2');

      chart.on('datazoom', this.chartScroll1)
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart1 = chart;

      this.setData({
        isLoaded: true,
        isDisposed: false
      });

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  // 点击按钮后初始化图表
  init: function () {
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      chart.on('datazoom', this.chartScroll)
      this.setOption(chart, '1');

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      this.setData({
        isLoaded: true,
        isDisposed: false
      });

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  chartScroll(e) {
    this.chart.dispatchAction({
      type: 'hideTip'
    })
  },
  chartScroll1(e) {
    this.chart1.dispatchAction({
      type: 'hideTip'
    })
  },
  setOption(chart, valtype) {



    wx.request({
      url: 'https://babyplanet.isv-dev.youzan.com/api/bMIData/show',
      data: {
        babyId: this.data.babyId,
        type: 1
      },
      method: 'post',
      success: (res) => {
        if (res.data.code == 200) {
          let seriesAtrr = [

            {
              name: '宝宝',
              color: '#3065bc',
              type: 'line',
              connectNulls: true,
              symbol: 'circle',
              symbolSize: 8,
              smooth: true,
              itemStyle: {
                normal: {
                  label: {
                    show: true // 在折线拐点上显示数据
                  },
                  lineStyle: {
                    width: 2,
                  }
                }
              },
              data: []
            }, {
              name: '+3SD',
              color: '#ed7100',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            },
            {
              name: '+2SD',
              color: '#ed7100',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            }, {
              name: '+1SD',
              color: '#ed7100',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            },
            {
              name: '中位数',
              color: '#ed7100',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            },
            {
              name: '-1SD',
              color: '#008236',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            },
            {
              name: '-2SD',
              color: '#3a77ff',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            },
            {
              name: '-3SD',
              color: '#927626',
              type: 'line',
              symbol: 'none',
              itemStyle: {
                normal: {
                  lineStyle: {
                    width: 1,
                    type: 'dashed'
                  }
                }
              },
              data: []
            }
          ]
          let xAxisData = []
          let attr = []

          let eStart = 0
          let eEnd = 14
          if (valtype == 1) {
            res.data.data.sgqx.some((item, index) => {
              attr.push(item.monthCount)

              item.monthCount1=item.monthCount
              if (index == 0) {
                item.monthCount = '月'
                item.monthCount1 = '月龄'
              }
              if (item.isHide == 1) {
                item.monthCount = ''
                item.monthCount1 = item.monthCount1+'月龄'
              }
              if (index == 13) {
                item.monthCount = '（1岁）'
                item.monthCount1 = '1岁'
              }
              if (index == 25) {
                item.monthCount = '（2岁）'
                item.monthCount1 = '2岁'
              }
              if (index == 37) {
                item.monthCount = '（3岁）'
                item.monthCount1 = '3岁'
              }
              if (index == 49) {
                item.monthCount = '（4岁）'
                item.monthCount1 = '4岁'
              }
              if (index == 61) {
                item.monthCount = '（5岁）'
                item.monthCount1 = '5岁'
              }
              if (index == 73) {
                item.monthCount = '（6岁）'
                item.monthCount1 = '6岁'
              }
              xAxisData.push(item.monthCount)

              seriesAtrr[1].data.push(Number(item.sd1))
              seriesAtrr[2].data.push(Number(item.sd2))
              seriesAtrr[3].data.push(Number(item.sd3))
              seriesAtrr[4].data.push(Number(item.sd4))
              seriesAtrr[5].data.push(Number(item.sd5))
              seriesAtrr[6].data.push(Number(item.sd6))
              seriesAtrr[7].data.push(Number(item.sd7))

              if (!item.babyValue) {

                seriesAtrr[0].data.push('')
              } else {

                eEnd = index + 5
                eStart = index - 9 < 0 ? 0 : index - 9
                seriesAtrr[0].data.push(Number(item.babyValue))
              }
            })

          } else {

            res.data.data.tzqx.some((item, index) => {
              attr.push(item.monthCount)
              if (index == 0) {
                item.monthCount = '月'
              }
              if (index == 13) {
                item.monthCount = '（1岁）'
              }
              if (index == 25) {
                item.monthCount = '（2岁）'
              }
              if (index == 37) {
                item.monthCount = '（3岁）'
              }
              if (index == 49) {
                item.monthCount = '（4岁）'
              }
              if (index == 61) {
                item.monthCount = '（5岁）'
              }
              if (index == 73) {
                item.monthCount = '（6岁）'
              }
              if (item.isHide == 1) {
                item.monthCount = ''
              }
              xAxisData.push(item.monthCount)
              // xAxisData.push((item.monthCount + '月))

              seriesAtrr[1].data.push(Number(item.sd1))
              seriesAtrr[2].data.push(Number(item.sd2))
              seriesAtrr[3].data.push(Number(item.sd3))
              seriesAtrr[4].data.push(Number(item.sd4))
              seriesAtrr[5].data.push(Number(item.sd5))
              seriesAtrr[6].data.push(Number(item.sd6))
              seriesAtrr[7].data.push(Number(item.sd7))

              if (!item.babyValue) {

                seriesAtrr[0].data.push('')
              } else {
                eEnd = index + 5
                eStart = index - 9 < 0 ? 0 : index - 9
                seriesAtrr[0].data.push(Number(item.babyValue))
              }
            })
          }
          console.log(seriesAtrr, 12112)
          var option = {
            title: {
              text: '',
              left: 'center'
            },
            // legend: {
            //   data: ['A', 'B', 'C'],
            //   top: 50,
            //   left: 'center',
            //   backgroundColor: 'red',
            //   z: 100
            // },
            grid: {
              containLabel: true
            },
            tooltip: {
              show: true,
              triggerOn: 'click',
              trigger: 'axis',
              padding: 6,
              textStyle: {
                fontSize: 11
              },
              confine: true,
              formatter: (params) => {
                var str = '';
				
				
				if (valtype == 1) {
                str = res.data.data.sgqx[params[0].dataIndex].monthCount1 + '\n'
					
				}else{
                str = res.data.data.tzqx[params[0].dataIndex].monthCount1 + '\n'
					
				}
                params.forEach(item => {
                  console.log(item, 12122)
                  str += item.marker + " " + item.seriesName + ":" + item.value + '\n'
                })
                return str
              }
            },
            dataZoom: [{
                type: 'inside', // 支持内部鼠标滚动平移
                startValue: eStart,
                endValue: eEnd,
                xAxisIndex: [0],
                zoomLock: 'false',
                filterMode: 'none',
              }

            ],
            xAxis: {
              boundaryGap: false,
              type: 'category',
              axisLine: {
                show: true,
              },
              // //网格线
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'solid', //y轴分割线类型
                  color: '#d9dadb',
                  width: 1,
                },
              },
              // 坐标刻度线
              axisTick: {
                show: false,
              },
              axisLabel: {
                fontSize: 10,
                color: '#285fb9',
                interval: 0,
                // minInterval:1
              },
              data: xAxisData
            },
            yAxis: {
              x: 'center',
              interval: valtype == 1 ? 10 : 4,
              type: 'value',
              min: valtype == 1 ? 42 : 2,
              max: valtype == 1 ? 142 : 42,
              axisLine: {
                show: true,
              },
              axisLabel: {
                fontSize: 12,
                color: '#285fb9',
                interval: 10,
                // minInterval:1
              }
              // show: false
            },
            series: seriesAtrr,
            grid: {
              x: 50,
              y: 20,
              x2: 30,
              y2: 60
            },
          };

          chart.setOption(option);
        }
      }
    })
  },
  changeCate(e) {
    let idx = e.currentTarget.dataset.index
    this.setData({
      curCate: idx
    })
    this.init()
    this.init1()

  },
  toDel(e) {
    let idx = e.currentTarget.dataset.index

    let that = this
    wx.showModal({
      title: '提示',
      content: '确定删除该记录吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: getApp().globalData.apiBaseUrl + 'babyBMI/delete',
            data: {
              id: that.data.infoList[idx].id
            },
            method: 'post',
            success: (res) => {
              if (res.data.code == 200) {
                that.data.infoList.splice(idx, 1)
                that.setData({
                  infoList: that.data.infoList
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  toAdd() {
    wx.navigateTo({
      url: '/pages/bodyAdd/index?babyId=' + this.data.babyId,
    })
  },
  toEdit(e) {
    wx.navigateTo({
      url: '/pages/bodyAdd/index?babyId=' + this.data.babyId + '&id=' + e.currentTarget.dataset.id,
    })
  },

  initData() {

    wx.request({
      url: 'https://babyplanet.isv-dev.youzan.com/baby/view',
      data: {
        id: 32
      },
      method: 'get',
      success: (res) => {
        console.log(res, 122)
        if (res.data.code == 200) {
          let birth = res.data.data.birthday
          wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/babyBMI/findList',
            data: {
              babyId: this.data.babyId
            },
            method: 'post',
            success: (res) => {
              if (res.data.code == 200) {


                res.data.data.some(item => {
                  if (item.measureDate) {
                    item.birthday = getAge(item.measureDate, birth)
                  }
                })
                this.setData({
                  infoList: res.data.data
                })
              }
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})